package com.fc.advbox.service.impl;

import com.fc.advbox.dao.UserPointDao;
import com.fc.advbox.dao.UserPointHistoryDao;
import com.fc.advbox.entity.UserPointEntity;
import com.fc.advbox.entity.UserPointHistoryEntity;
import com.fc.advbox.service.IUserPointService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by E7450 on 2018/6/27.
 */
@Service("userPointService")
public class UserPointServiceImpl implements IUserPointService {

    @Autowired
    private UserPointDao userPointDao;

    @Autowired
    private UserPointHistoryDao userPointHistoryDao;

    @Override
    public UserPointEntity queryObject(Long historyId) {
        return userPointDao.queryObject(historyId);
    }

    @Override
    public UserPointEntity queryByUserId(Long userId){
        return userPointDao.queryByUserId(userId);
    }
    @Override
    public List<UserPointEntity> queryList(Map<String, Object> params) {
        return userPointDao.queryList(params);
    }

    @Override
    public List<UserPointHistoryEntity> queryHistoryList(Map<String, Object> params) {
        return userPointHistoryDao.queryList(params);
    }

    @Override
    public void save(UserPointEntity point) {
        userPointDao.save(point);
        saveHistory(point.getPoint(), point.getUserId(), "");
    }

    @Override
    public void save(UserPointEntity point, String desc) {
        userPointDao.save(point);
        saveHistory(point.getPoint(), point.getUserId(), desc);
    }

    private void saveHistory(Integer pointValue, Long userId, String desc){
        UserPointHistoryEntity history = new UserPointHistoryEntity();
        if(pointValue == 0){
            return;
        }
        history.setPoint(pointValue);
        history.setUpdDate(new Date());
        history.setUserId(userId);
        if(desc != null){
            history.setDescn(desc);
        }
        userPointHistoryDao.save(history);
    }
    @Override
    public void delete(Long historyId) {
        userPointDao.delete(historyId);
    }

    @Override
    public void deleteBatch(Long[] historyIds) {
        userPointDao.deleteBatch(historyIds);
    }

    @Override
    public void addPoint(UserPointEntity userPoint, String desc) {
        // 1. 先给用户增加积分
        UserPointEntity up = userPointDao.queryByUserId(userPoint.getUserId());
        if(up == null){
            userPointDao.save(userPoint);
        }
        userPointDao.addPoint(userPoint);

        // 2. 记录积分变化，在积分历史表中新增一条记录
        saveHistory(userPoint.getPoint(), userPoint.getUserId(), desc);
    }
}
